package Controller

import (
	"back_go/DAO"
	models "back_go/DAO/model"
	"back_go/Middleware"
	"back_go/Response"
	"context"
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"math"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

// ShopNoticePage 公告列表
/*
  参数：
  	current: 当前页码，默认为1
	size: 每页数量，默认为10
    status: 状态
	isTop: 是否置顶
	title: 标题
    return: 公告列表
*/
func ShopNoticePage(c *gin.Context) {
	var engine = DAO.Engine
	var notices []models.TzNotice
	var notice models.TzNotice

	currentStr := c.Query("current")
	sizeStr := c.Query("size")
	status := c.Query("status")
	isTop := c.Query("isTop")
	title := c.Query("title")
	page, err := strconv.Atoi(currentStr)

	var count int64
	if err != nil || page < 1 {
		page = 1
	}

	size, err := strconv.Atoi(sizeStr)
	if err != nil || size < 1 {
		size = 10
	}

	conds := make([]string, 0, 3) // 直接使用 string 类型的切片
	params := make([]interface{}, 0, 3)
	query := "1=1"

	if status != "" {
		conds = append(conds, "status=?")
		params = append(params, status)

		query += " AND " + conds[len(conds)-1]
	}

	if isTop != "" {
		conds = append(conds, "is_top=?")
		params = append(params, isTop)
		query += " AND " + conds[len(conds)-1] // 这里不需要再次检查 query 是否为 "1=1"，因为已经添加了至少一个条件
	}

	if title != "" {
		conds = append(conds, "title like ?")
		params = append(params, "%"+title+"%")
		query += " AND " + conds[len(conds)-1]
	}

	// 执行查询
	err = engine.Where(query, params...).Limit(size, (page-1)*size).Find(&notices)
	if err != nil {
		// 处理查询错误
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 计算总数
	count, err = engine.Where(query, params...).Count(&notice)
	if err != nil {
		// 处理计数错误
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 如果没有结果，将 notices 设置为空切片，而不是 nil
	if len(notices) == 0 {
		notices = []models.TzNotice{}
	}

	// 构造响应
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code: "00000",
		Data: PageParam1[models.TzNotice]{
			Current: page,
			Total:   count,
			Size:    size,
			Records: notices,
			Pages:   int(math.Ceil(float64(count) / float64(size))),
		},
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

// GetNoticeById 通过id获取公告信息
/*
  参数：
  	id: 公告id
    return: 公告信息
*/
func GetNoticeById(c *gin.Context) {
	var engine = DAO.Engine
	id := c.Param("id")

	var notice models.TzNotice
	_, err := engine.Where("id=?", id).Get(&notice)

	if err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
		})
		return
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Data:      notice,
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

// SaveNotice 保存公告信息
/*
  参数：
  	notice: 公告信息
    return: 公告信息
*/
func SaveNotice(c *gin.Context) {
	var engine = DAO.Engine
	var notice models.TzNotice
	_ = c.ShouldBindJSON(&notice)
	notice.PublishTime = time.Now()
	//fmt.Println("id",notice.Id,"标题",notice.Title,"内容",notice.Content,"status",notice.Status,"IsTop",notice.IsTop)
	_, err := engine.Insert(&notice)
	if err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Fail:      true,
			Success:   false,
		})
		return
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Data:      nil,
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

// UpdateNotice 修改公告信息
/*
  参数：
  	notice: 公告信息
    return: 公告信息
*/
func UpdateNotice(c *gin.Context) {
	var engine = DAO.Engine
	var notice models.TzNotice
	_ = c.ShouldBindJSON(&notice)
	var updateNotice models.TzNotice

	updateNotice.Id = notice.Id
	updateNotice.ShopId = notice.ShopId
	updateNotice.Title = notice.Title
	updateNotice.Content = notice.Content
	updateNotice.Status = notice.Status
	updateNotice.IsTop = notice.IsTop
	updateNotice.PublishTime = notice.PublishTime
	updateNotice.UpdateTime = time.Now()
	//fmt.Println("id", updateNotice.Id, "标题", updateNotice.Title, "内容", updateNotice.Content, "status", updateNotice.Status, "IsTop", updateNotice.IsTop)
	sql := `UPDATE tz_notice
SET shop_id =?,
    title =?,
    content =?,
    status =?,
    is_top =?,
    update_time =?
WHERE id =?;`

	_, err := engine.Exec(sql, updateNotice.ShopId, updateNotice.Title, updateNotice.Content, updateNotice.Status, updateNotice.IsTop, time.Now(), updateNotice.Id)

	if err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
		})
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Data:      nil,
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

// DeleteNoticeById 删除公告信息
/*
  参数：
  	id: 公告id
    return: 公告信息
*/
func DeleteNoticeById(c *gin.Context) {
	var engine = DAO.Engine
	id := c.Param("id")

	var notice models.TzNotice
	_, err := engine.Where("id =?", id).Select("content").Get(&notice)

	//删除minio的图片

	re := regexp.MustCompile(`([a-zA-Z0-9-]+\.jpg)`)
	matches := re.FindAllStringSubmatch(notice.Content, -1)
	for _, match := range matches {
		if len(match) > 1 {
			filename := match[1]
			err := Middleware.MinioClient.RemoveObject(context.Background(), "admin-file", filename, minio.RemoveObjectOptions{})
			if err != nil {
				// 处理删除失败的情况
				// 可以选择记录错误日志或者返回错误信息给调用方
			}
		}
	}
	_, err = engine.Where("id=?", id).Delete(&models.TzNotice{})
	if err != nil {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
		})
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Data:      nil,
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}
